import React, { useEffect, useMemo, useState } from 'react';
import ReactDOM, { unmountComponentAtNode } from 'react-dom';
import styles from './CityPicker.less';
import { PickerScroll, ICityJson } from './PickerScroll';
import CityJson from './area.json';
import { isEmpty } from '@/utils/common';

interface IDCityPIcker {
  defaultValue?: string
  onSelect: (cityCode: Array<string>, cityName: Array<string>) => void
}

let nodeWrap: HTMLDivElement;

/* 初始化外部容器 */
const initWrap = () => {
  if (!nodeWrap) {
    nodeWrap = document.createElement('div');
    document.body.appendChild(nodeWrap);
  }
  // nodeWrap.className = styles.node_wrap;
  const nodeBox = document.createElement('div');
  nodeWrap.appendChild(nodeBox);
  return nodeBox;
};

interface IDDMain extends IDCityPIcker {
  wrapNode: HTMLDivElement
  elemNode: Element | DocumentFragment
}

/** 判斷是否為promise */
function isPromise(obj: any) {

  return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';

}

const NodeMain: React.FC<IDDMain> = props => {
  let init = false;
  const { elemNode, wrapNode, onSelect, defaultValue } = props;
  const [defaultCity, defaultArea] = defaultValue ? defaultValue.split(',') : ['4', '26']
  const [cityCode, setCityCode] = useState<string>(defaultCity);
  const [areaCode, setAreaCode] = useState<string>(defaultArea);
  const [cityIndex, setCityIndex] = useState<number>(0);
  const [areaIndex, setAreaIndex] = useState<number>(0);
  const [areaData, setAreaData] = useState<Array<ICityJson>>()

  // 卸载
  const unmount = useMemo(() => {
    return () => {
      if (elemNode && wrapNode && init) {
        unmountComponentAtNode(elemNode);
        wrapNode.removeChild(elemNode);
      }
    };
  }, [elemNode, wrapNode]);

  // 确认
  const handleConfirm = () => {
    init = true
    if (!onSelect) {
      unmount();
      return false;
    }
    let confirmFn: any = onSelect(
      [cityCode, areaCode],
      [CityJson[cityIndex].label, CityJson[cityIndex].children[areaIndex].label]
    );
    if (isPromise(confirmFn)) {
      confirmFn.then((res: boolean) => {
        res && unmount();
      })
    } else {
      unmount()
    }
  }

  const handleCityChange = (cityCode: string, index: number) => {
    setCityIndex(index)
    setCityCode(cityCode)
    setAreaCode(CityJson[index].children[0].value)
    setAreaData(CityJson[index].children)
  }

  useEffect(() => {
    CityJson.forEach(item => {
      if (item.value === cityCode) {
        setAreaData(item.children)
      }
    })
    setTimeout(() => {
      init = true
    }, 300);
  }, [])

  return (
    <>
      <div className={styles.node_mask} onClick={unmount}></div>
      <div className={styles.node_main}>
        <div className={styles.node_head}>
          <h3>請選擇地區</h3>
          <button className={styles.confirm} onClick={handleConfirm}>確認</button>
        </div>
        <div className={styles.node_box}>
          <PickerScroll type="city" data={CityJson} onSelect={handleCityChange} current={cityCode} />
          <PickerScroll type="area" data={areaData} onSelect={(res, index) => { setAreaIndex(index); setAreaCode(res) }} current={areaCode} />
        </div>
      </div>
    </>
  );
}

/* 实现 */
const show = (params: IDCityPIcker) => {
  let elemNode = initWrap();
  // nodeWrap.className = styles.message_box;
  ReactDOM.render(
    <NodeMain elemNode={elemNode} wrapNode={nodeWrap} {...params} />,
    elemNode,
  );
};

const getName = (code: string) => {
  if (isEmpty(code)) return undefined;
  let codeArr = code.split(',');
  let nameArr: Array<string> = [];
  CityJson.forEach(item => {
    if (item.value == codeArr[0]) {
      nameArr[0] = item.label
      item.children.forEach(child => {
        if (child.value === codeArr[1]) {
          nameArr[1] = child.label
        }
      })
    }
  })
  return nameArr
}

export default {
  show,
  getName
}